<template>
  <div>
    <el-form ref="deptForm" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in managerList"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="submit">确定</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments } from '@/api/departments'

export default {
  name: '',
  data() {
    return {
      managerList: [],
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入部门编码', trigger: 'blur' }],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  created() {
    this.getEmp()
  },
  // 获取数据
  methods: {
    async getEmp() {
      const { data } = await getEmployeeSimple()
      this.managerList = data
    },
    submit() {
      this.$refs.deptForm.validate((valid) => {
        if (valid) {
          this.doAdd()
        }
      })
    },
    async doAdd() {
      const res = await addDepartments(this.form)
      this.form.pid = this.id
      if (res.code === 10000) {
        this.$emit('success')
        // 清空数据
        this.form = {
          name: '',
          code: '',
          manager: '',
          introduce: '',
          pid: ''
        }
      }
    },
    cancel() {}
  }
}
</script>
<style lang="less" scoped></style>
